import { bindUserPhoneNumber } from '../../services/user';
import Message from '../../miniprogram_npm/tdesign-miniprogram/message/index';
import { login } from '../../utils/auth';

const app = getApp<IAppOption>()

Page({
  data: {
    defaultAvatarUrl: 'https://cdn-we-retail.ym.tencent.com/miniapp/usercenter/icon-user-center-avatar@2x.png',
    userInfo: undefined,
    btnLoading: false
  },

  onLoad() {
    if (!app.globalData.userInfo) {
      // 回调用户信息
      app.userInfoReadyCallback = (result: any) => {
        this.setData({ userInfo: result });
      };
    }
  },

  // 返回上一页
  goBack() {
    const pages = getCurrentPages()
    if (pages.length > 1) {
      wx.navigateBack({ delta: 1 })
    } else {
      wx.reLaunch({ url: '/pages/index/index' })
    }
  },

  // 获取手机号
  getPhoneNumber(e: any) {
    if (e.detail.errMsg === 'getPhoneNumber:ok') {
      this.setData({ btnLoading: true })
      bindUserPhoneNumber(e.detail.code).then(async () => {
        // 再次登陆, 刷新信息
        const userInfo = await login();
        app.globalData.userInfo = userInfo as any;
        this.setData({ btnLoading: false });
        this.goBack();
      }).catch((err) => {
        this.setData({ btnLoading: false });
        this.showErrorMessage(err);
      });
    }
  },

  // 展示错误信息
  showErrorMessage(content: string) {
    Message.error({
      context: this,
      offset: [20, 32],
      content
    })
  }
})